﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace CivilleWebRole
{
    public partial class ViewQRCodes : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/NotAuthorized.aspx");
            }
        }

        protected void GenerateQRCodes(object sender, EventArgs e)
        {
            if (TasksDDL.SelectedItem == null)
            {
                return;
            }

            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT COUNT(*) FROM [QRCode] WHERE [TaskID] = '" + TasksDDL.SelectedItem.Value + "' AND [Status] != 'false'";
            connection.Open();
            int QRCodesNumber = (int)command.ExecuteScalar();
            
            if (QRCodesNumber < 20)
            {
                QRCodeGenerator generator = new QRCodeGenerator();
                for (int i = 0; i < 20 - QRCodesNumber; i++)
                {
                    String code = generator.generateRandomString();
                    SqlCommand createQRCodescommand = connection.CreateCommand();
                    createQRCodescommand.CommandText = "INSERT INTO [QRCode] ([Code], [Status], [TaskID]) VALUES ('" + code + "', 'true', '" + TasksDDL.SelectedItem.Value + "')";
                    createQRCodescommand.ExecuteNonQuery();
                }
            }

            connection.Close();
        }
    }
}